#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//编译：g++ -o bin/run_fit_curve_v3 fit_curve_v3.c -lm
//编译运行：g++ -o bin/run_fit_curve_v3 c/fit_curve_v3.c -lm && ./bin/run_fit_curve_v3
//对比第二版，三点拟合变成四点拟合


// 高斯消元法函数
void gaussianElimination(double matrix[4][3], int n) {
    double factor;
    int i, j, k;

    // 高斯消元
    for (k = 0; k < n - 1; k++) {
        // 寻找主元
        int max_row = k;
        for (i = k + 1; i < n; i++) {
            if (fabs(matrix[i][k]) > fabs(matrix[max_row][k])) {
                max_row = i;
            }
        }
        if (max_row != k) {
            for (j = 0; j <= n; j++) {
                double temp = matrix[k][j];
                matrix[k][j] = matrix[max_row][j];
                matrix[max_row][j] = temp;
            }
        }

        for (i = k + 1; i < n; i++) {
            factor = matrix[i][k] / matrix[k][k];
            for (j = k; j <= n; j++) {
                if (j != k) {
                    matrix[i][j] -= factor * matrix[k][j];
                }
            }
        }
    }

    // 回代求解
    for (i = n - 1; i >= 0; i--) {
        for (j = i + 1; j < n; j++) {
            matrix[i][n] -= matrix[j][n] * matrix[i][j];
        }
        matrix[i][n] /= matrix[i][i];
    }
}

// 函数来求解二次曲线方程的系数
void solveQuadraticCurve(double points[4][2], double *coefficients) {
    double matrix[4][3];

    // 构建增广矩阵
    for (int i = 0; i < 4; i++) {
        matrix[i][0] = points[i][0] * points[i][0]; // x^2
        matrix[i][1] = points[i][0]; // x
        matrix[i][2] = points[i][1]; // y
    }

    // 调用高斯消元法函数
    gaussianElimination(matrix, 4);

    // 提取结果
    coefficients[0] = matrix[0][0]; // a
    coefficients[1] = matrix[1][1]; // b
    coefficients[2] = matrix[2][2]; // c
}

int main() {
    // 给定的四个点
    double points[4][2] = {
        {79758, 19.43},
        {61358, 14.349},
        {40887, 9.491},
        {22661, 5.434}
    };

    // 存储系数
    double coefficients[3] = {0, 0, 0};

    // 执行高斯消元拟合
    solveQuadraticCurve(points, coefficients);

    // 打印结果
    printf("拟合的二次曲线方程为: y = %f * x^2 + %f * x + %f\n", coefficients[0], coefficients[1], coefficients[2]);

    return 0;
}






